import { createRouter, createWebHashHistory } from "vue-router";
import Login from "@/views/Login.vue";
import Charts from "@/views/Charts.vue";
import Home from "@/views/Home.vue";
import Pay from "@/views/Pay.vue";
import Remind from "@/views/Remind.vue";
import Level from "@/views/Level.vue";
import OrderDefault from "@/views/OrderDefault.vue";
import { useAuthStore } from "@/stores/authStore";
import instance from '@/api';
import { ElMessage } from 'element-plus';

// 验证 token 有效性
const validateToken = async (token: string): Promise<boolean> => {
  try {
    // 这里使用一个验证 token 的接口
    const response = await instance.get('/api/auth/validate-token');
    return response.status === 200;
  } catch (error) {
    return false;
  }
};

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/no-permission',
      name: 'no-permission',
      component: () => import('@/views/NoPermission.vue'),
      meta: { title: '无权限访问' }
    },
    {
      path: "/",
      name: "login",
      component: Login,
      meta: { title: "登录" },
    },
    {
      path: "/level",
      name: "level",
      component: Level,
      redirect: "/level/home",
      meta: { requiresAuth: true },
      children: [
        {
          path: "home",
          name: "home",
          component: Home,
          meta: { title: "首页" },
          children: [
            {
              path: "", // 空路径，表示默认子路由，访问 /home 时会加载 Charts 组件
              name: "home.default", // 添加名称
              component: Charts,
            },
            {
              path: "pay", // 相对路径，实际路径是 /home/pay
              name: "pay",
              component: Pay,
              meta: { title: "未付款" },
            },
            {
              path: "remind",
              name: "remind",
              component: Remind,
              meta: { title: "到期提醒" },
            },
            {
              path: "complaint",
              name: "complaint",
              component: () => import("@/views/Complaint.vue"),
              meta: { title: "投诉管理" },
            },
          ],
        },
        {
          path: "order",
          name: "order",
          component: () => import("@/views/Order.vue"),
          meta: { 
            title: "订单管理",
          },
          children: [
            {
              path: "", // 空路径，表示默认子路由，访问 /order 时会加载 OrderDefault 组件
              name: "order.default", // 添加名称
              component: OrderDefault,
            },
            {
              path: "createOrder",
              name: "create",
              component: () => import("@/views/CreateOrder.vue"),
              meta: { title: "新建订单" },
            },
            {
              path: "orderDetail/:id",
              name: "orderDetail",
              component: () => import("@/views/OrderDetail.vue"),
              meta: { title: "订单详情" },
            },
          ],
        },
        {
          path: "member",
          name: "member",
          component: () => import("@/views/Member.vue"),
          meta: {
            title: "会员管理",
          },
          children: [
            {
              path: "",
              name: "member.default", // 添加名称
              component: () => import("@/views/MemberVip.vue"),
            }
          ],
        },
        {
          path: "staff",
          name: "staff",
          component: () => import("@/views/Staff.vue"),
          meta: { 
            title: "员工管理",
            permissions: 'employee'
          },
          children: [
            {
              path: "",
              name: "staff.default",
              component: () => import("@/views/StaffManage.vue"),
            },
          ],
        },
        {
          path: "shop",
          name: "shop",
          component: () => import("@/views/Shop.vue"),
          meta: { 
            title: "店铺管理",
            permissions: 'shop'
          },
          children: [
            {
              path: "",
              name: "shop.default",
              component: () => import("@/views/ShopManage.vue"),
            },
          ],
        },
        {
          path: "statistics",
          name: "statistics",
          component: () => import("@/views/Statistics.vue"),
          meta: { 
            title: "数据统计",
            permissions: 'data'  
          },
          children: [
            {
              path: "",
              name: "statistics.default",
              component: () => import("@/views/StatisticsManage.vue"),
            },
          ],
        },
        {
          path: "permission",
          name: "permission",
          component: () => import("@/views/Permission.vue"),
          meta: { 
            title: "权限管理",
            permissions: 'permissionManagement', // 特殊权限
            superAdminOnly: true // 仅超级管理员可访问
          },
          children: [
            {
              path: "", // 空路径，表示默认子路由，访问 /permission 时会加载 PermissionManage 组件
              name: "permission.default",
              component: () => import("@/views/PermissionManage.vue"),
            },
          ],
        },
      ],
    },
  ],
});
type PermissionType = 'employee' | 'shop' | 'data';
// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()
  const token = authStore.token;
  
  // 检查路由是否需要认证
  if (to.meta.requiresAuth) {
    if (!token) {
      next('/') // 如果需要认证但未登录，重定向到登录页
      return
    }
    
    // 验证 token 有效性
    const isValid = await validateToken(token);
    if (!isValid) {
      authStore.clearToken(); // 清除无效的 token
      ElMessage.warning('身份验证已过期，请重新登录');
      next('/') // 重定向到登录页
      return
    }
  }

  if (to.name === 'login') {
    if (token) {
      // 验证 token 有效性
      const isValid = await validateToken(token);
      if (isValid) {
        next('/level') // 已登录且 token 有效，跳转到首页
      } else {
        authStore.clearToken(); // 清除无效的 token
        ElMessage.warning('身份验证已过期，请重新登录');
        next() // token 无效，允许访问登录页
      }
    } else {
      next() // 未登录，允许访问登录页
    }
    return
  }

  // 权限验证
  if (authStore.isSuper) {
    next() // 超级管理员放行所有
    return
  }
  const requiredPerm = to.meta.permissions
  
  if (!requiredPerm) {
    next() // 无需权限的页面
    return
  }
  // 检查对应权限字段
  const hasPermission = {
    'employee': authStore.canEmployee,
    'shop': authStore.canShop,
    'data': authStore.canData
  }[requiredPerm as PermissionType]
  hasPermission ? next() : next('/no-permission')
});
export default router;
